import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/utils/cache_utils.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';
import 'package:casdon/modules/me/data/repository/me_repository.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

final refreshProvider = StateProvider.autoDispose<UniqueKey>(
  (ref) => UniqueKey(),
);

final _logoutLoadingProvider = StateProvider.autoDispose<bool>((ref) => false);

@RoutePage()
class MeSettingScreen extends ConsumerWidget {
  const MeSettingScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    ref.watch(refreshProvider);
    final isLogoutLoading = ref.watch(_logoutLoadingProvider);
    return FullscreenLoadingOverlay(
      loading: isLogoutLoading,
      child: Scaffold(
        appBar: CommonAppBar(title: "设置"),
        body: Container(
          color: context.colorScheme.surface,
          child: Column(
            children: [
              _buildGap(context),
              FormFieldItem(
                label: '账号与安全',
                isRequired: false,
                showBottomDivider: false,
                isEditable: false,
                showArrow: true,
                backgroundColor: Colors.white,
                onTap: () => _goAccountSettingPage(context, ref),
              ),
              _buildGap(context),
              FutureBuilder<double>(
                future: CacheUtils.getCacheSizeMB(),
                builder: (context, snapshot) {
                  return FormFieldItem(
                    label: '清空缓存',
                    showBottomDivider: false,
                    isRequired: false,
                    hintText: '${(snapshot.data ?? 0).toStringAsFixed(2)} MB',
                    showArrow: true,
                    isEditable: false,
                    backgroundColor: Colors.white,
                    onTap: () => _handelClearAppCache(context, ref),
                  );
                },
              ),

              _buildGap(context),
              FormFieldItem(
                label: '关于凯度生活家',
                showBottomDivider: false,
                isRequired: false,
                isEditable: false,
                showArrow: true,
                backgroundColor: Colors.white,
                onTap: () => _goAppAboutPage(context, ref),
              ),
              const Spacer(),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 86.w),
                child: PrimaryButton(
                  text: "退出登录",
                  onPressed: () => _logOut(context, ref),
                ),
              ),
              const SizedBox(height: 130),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGap(BuildContext context) {
    return ColoredBox(
      color: context.colorScheme.surface,
      child: SizedBox(height: 8, width: double.infinity),
    );
  }

  void _goAccountSettingPage(BuildContext context, WidgetRef ref) {
    AccountSecurityRoute().push(context);
  }

  void _goAppAboutPage(BuildContext context, WidgetRef ref) async {
    AppAboutRoute().push(context);
  }

  void _handelClearAppCache(BuildContext context, WidgetRef ref) async {
    if (context.mounted == false) {
      return;
    }
    final ret = await showCustomConfirmDialog(
      context: context,
      content: "确定清空缓存？",
    );
    if ((ret ?? false) && context.mounted) {
      CacheUtils.clearCache();
      ref.invalidate(refreshProvider);
    }
  }

  void _logOut(BuildContext context, WidgetRef ref) async {
    if (context.mounted == false) {
      return;
    }
    final ret = await showCustomConfirmDialog(
      context: context,
      content: "确定退出账户吗？",
    );
    if ((ret ?? false) && context.mounted) {
      ref.read(_logoutLoadingProvider.notifier).state = true;
      try {
        await ref.read(tuyaLoginProvider.notifier).logOut();
        await ref.read(meRepositoryProvider).logOut();
        await ref.read(authStorageProvider.notifier).clear();
        ref.watch(unifiedDeviceNotifierProvider.notifier).clear();
        if (context.mounted) {
          context.router.replaceAll(const [AccountInputRoute()]);
        }
      } finally {
        ref.read(_logoutLoadingProvider.notifier).state = false;
      }
    }
  }
}
